<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Exceptions\Admin\ProductException;

use App\Interfaces\CategoryService;
use App\Interfaces\ProductSkuService;

use App\Models\Category;
use App\Models\Product;
use App\Models\ProductAttribute;
use App\Models\ProductAttributeValue;
use App\Models\ProductSku;
use App\Models\Goods;
use App\Models\Brand;
use DB,Log;

/**
 * 产品product
 * @author   Leen
 * @date     2016/03/28
 */
class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, Category $category)
    {
        //$product = Product::all();
        $product = Product::paginate(10);

        foreach ($product as $key => $value) {
            $product_id = $value->id;
            $product_goods = ProductSku::where('product_id', $product_id)
                            ->leftJoin('goods', 'product_sku.goods_id', '=', 'goods.goods_id' )
                            ->get();

            $product[$key]->product_goods = $product_goods->toArray();

        }//end foreach()

        return view('admin.product.index',compact(['product', 'category']));

    }//end func index()

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request, Category $category)
    {
        //
        $search = array('cat_id'=>0);
        $product = Product::all();
        return view('admin.product.create',compact(['product', 'category', 'search']));
    }

    /**
     * 添加产品
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  [array] $attribue_value_arr              [产品的属性及对应属性值数组]
     * @param  [array] $goods_value_arr                 [产品要关联的商品及属性值组的数组]
     * @return \Illuminate\Http\Response
     */
    //public function store($attribue_value_arr, $goods_value_arr=array(), Request $request, ProductSkuService $productSkuService)
    public function store(Request $request)
    {

        //第一步：根据产品所属分类id插入产品表
        $return = ['status'=>1, 'message'=>'', 'data'=>''];
        $product['cat_id'] = @$request->cat_id;
        $product['name'] = @$request->product_name;
        $attribute_value_arr = @$request->attribute_value_arr;
        $goods_value_arr = @$request->goods_value_arr;


        if(empty($product['cat_id'])){

            $return['status'] = 0;
            $return['message'] = '分类id不能为空';
            return $return;
        }

        if(empty($product['name'])){

            $return['status'] = 0;
            $return['message'] = '产品名称不能为空';
            return $return;
        }

        if(empty($attribute_value_arr)){

            $return['status'] = 0;
            $return['message'] = '属性及对应的属性值数组不能为空';
            return $return;
        }

        $return['data']['cat_id'] = $product['cat_id'];

        DB::beginTransaction();//开启事务,开始批量操作
        try {
            $products = Product::create($product);

            if($products){
                $product_id = $products->id;
                $return['data']['product_id'] = $product_id;
            }else{

                $return['status'] = 0;
                $return['message'] = '产品创建失败';
                return $return;
            }//end if()

            //第二步：保存产品的属性和属性值
            $result = $this->storeAttributeValue($product_id, $attribute_value_arr);

        } catch (ProductException $e) {
            DB::rollback();
            throw new ProductException("产品创建失败");
        }
        DB::commit();

        //第三步：如果有要关联的商品，将商品id和对应的属性及属性值组信息插入到product_sku表中
        if (!empty($goods_value_arr)) {

            try {
                $productSku = $this->addRelation($product_id, $goods_value_arr);
            } catch (ProductException $e) {

                $return['status'] = 0;
                $return['message'] = $e->getMessage();

                return $return;
            }
        }//end if()

        return $return;
    }//end func store()


    /**
     * 保存产品的属性和对应的属性值
     *
     * @param  int  product_id  产品id
     * @param  array  attribue_value_arr  产品属性及属性值id数组，如：array:2 [ 6 => array:2 [ 0 => "6", 1 => "7"], 7 => array:2 [ 0 => "1", 1 => "2"]]
     * @return \Illuminate\Http\Response
     */
    public function storeAttributeValue($product_id, $attribue_value_arr)
    {

        //分类属性、分类属性对应的值
        foreach ($attribue_value_arr as $attribute_id => $values) {
            //将分类属性id插入到product_attribue表中
            $product_attribute = ProductAttribute::where('product_id', $product_id)->where('category_attribute_id', $attribute_id)->first();
            if(!$product_attribute){

                $product_attribute = ProductAttribute::create(['product_id'=>$product_id,'category_attribute_id'=>$attribute_id]);
            }//end if()
            $product_attribute_id = $product_attribute->id;
            //echo '<BR><BR>product_attribute_id:'.$product_attribute_id;

            foreach ($values as $key => $attribute_value) {

                //将分类属性值id插入到product_attribue_value表中
                $product_attribute_value = ProductAttributeValue::where('product_attribute_id', $product_attribute_id)->where('attribute_value', $attribute_value)->first();
                if(!$product_attribute_value){

                    $product_attribute_value = ProductAttributeValue::create(['product_attribute_id'=>$product_attribute_id,'attribute_value'=>$attribute_value]);
                }//end if()

                //echo '<BR>product_attribute_value_id:'.$product_attribute_value->id;
            }//end foreach()

        }//end foreach()

        return true;
    }//end func storeAttributeValue

    /**
     * 保存产品的sku
     * @method POST
     * @parse_url(http://afuyigou.app/admin/product/5/1346)
     *
     * @param  int  product_id  产品id
     * @param  int  goods_id    商品id
     * @param  array  attribute_group   商品的属性及属性值的集合，如：array:2 [ 6 => "7",7 => "1"]
     * @return \Illuminate\Http\Response
     */
    public function storeSku($product_id, $goods_id, Request $request, ProductSkuService $productSkuService)
    {
        //第三步：将商品id和对应的属性及属性值组信息插入到product_sku表中
        $return = ['status'=>0, 'message'=>'', 'data'=>''];

        $attribute_group = @$request->attribute_group;
        if(empty($attribute_group)){

            $return['message'] = '商品的属性及属性值的集合不能为空';
        }

        $goods = Goods::find($product_sku['goods_id']);
        if (empty($goods)) {

            $return['message'] = '要绑定的商品id['.$product_sku['goods_id'].']不存在';
            //throw new ProductException('要绑定的商品id['.$product_sku['goods_id'].']不存在');
            return $return;
        }//end if()

        $product_sku = $productSkuService->addRelation($product_id, $goods_id, $attribute_group);

        if($product_sku){

            $return['status'] = 1;
            $return['data'] = $product_sku;
        }

        return $return;

    }//end func storeAttributeValue

    /**
     * 修改产品
     * [根据产品id获取产品的属性、属性值以及关联的商品及商品对应的属性]
     * @param  [type] $product_id [description]
     * @return [type]             [description]
     */
    public function show($product_id)
    {
        /*$product_info = [];
        //第一步：根据产品id获取产品的属性及属性的值
        $products = Product::find($product_id);
        $product_info['name'] = $products->name;
        $product_info['cat_id'] = $products->cat_id;

        $product_attribute_arr = [];
        $product_attributes = ProductAttribute::where('product_id', $product_id)->get();
        if($product_attributes){

            foreach ($product_attributes as $key => $value) {

                $product_attribute_id = $value->id;
                $category_attribute_id = $value->category_attribute_id;
                //$product_attribute_arr[$key]['product_attribute'] = $category_attribute_id;
                $product_attribute_values = ProductAttributeValue::where('product_attribute_id', $product_attribute_id)->get();
                foreach ($product_attribute_values as $keys => $values) {
                    $attribute_value = $values->attribute_value;
                    $product_attribute_arr[$category_attribute_id][$keys] = $attribute_value;
                }//end foreach()

            }//end foreach()

        }//end if()
        $product_info['attribue_value_arr'] = $product_attribute_arr;

        $prodcut_sku_arr = [];
        $product_skus = ProductSku::where('product_id', $product_id)->get();
        if($product_skus){
            foreach ($product_skus as $key => $value) {
                $attribute_group = $value->attribute_group;
                $goods_id = $value->goods_id;

                $prodcut_sku_arr[$key]['goods_id'] = $goods_id;

                $valueIdArr = explode(',', $attribute_group);
                foreach ($valueIdArr as $keys => $value_id) {
                    $prodcut_sku_arr[$key]['attribute_value'][$keys] = $value_id;
                }
            }
        }
        $product_info['goods_value_arr'] = $prodcut_sku_arr;

        return $product_info;*/

    }//end func show

    /**
     * 编辑/修改产品
     *
     * [根据产品id获取产品的属性、属性值以及关联的商品及商品对应的属性]
     * @param  [type] $product_id [description]
     * @return [type]             [description]
     */
    public function edit($product_id,CategoryService $catgoryService, Category $category)
    {

        //第一步：根据产品id获取产品的属性及属性的值
        $products = Product::find($product_id);
        if(!empty($products)){

            $product_info = [];
            $product_info['product_id'] = $product_id;
            $product_info['product_name'] = $products->name;
            $product_info['cat_id'] = $products->cat_id;

            $category_attribute_value = $catgoryService->getCategoryAttribute($product_info['cat_id']);
            $product_info['category_attribute_value'] = $category_attribute_value;

            $product_attribute_arr = [];
            $product_attributes = ProductAttribute::where('product_id', $product_id)->get();
            if($product_attributes){

                foreach ($product_attributes as $key => $value) {

                    $product_attribute_id = $value->id;
                    $category_attribute_id = $value->category_attribute_id;
                    //$product_attribute_arr[$key]['product_attribute'] = $category_attribute_id;
                    $product_attribute_values = ProductAttributeValue::where('product_attribute_id', $product_attribute_id)->get();
                    foreach ($product_attribute_values as $keys => $values) {
                        $attribute_value = $values->attribute_value;
                        $product_attribute_arr[$category_attribute_id][$keys] = $attribute_value;
                    }//end foreach()

                }//end foreach()

            }//end if()
            $product_info['attribue_value_arr'] = $product_attribute_arr;

            $prodcut_sku_arr = [];
            $product_skus = ProductSku::where('product_id', $product_id)->get();
            if($product_skus){
                foreach ($product_skus as $key => $value) {
                    $attribute_group = $value->attribute_group;
                    $goods_id = $value->goods_id;

                    $prodcut_sku_arr[$key]['goods_id'] = $goods_id;

                    $valueIdArr = explode(',', $attribute_group);
                    foreach ($valueIdArr as $keys => $value_id) {
                        $prodcut_sku_arr[$key]['attribute_value'][$keys] = $value_id;
                    }
                }
            }
            $product_info['goods_value_arr'] = $prodcut_sku_arr;

        }//end if()
        return view('admin.product.edit',compact(['product_info', 'category_value', 'category']));

    }

    /**
     * 保存编辑的产品
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  [int] $product_id               [产品id]
     * @param  [array] $attribue_value_arr     [产品的属性及对应的属性值]
     * @param  [array] $attribute_group        [商品对应的属性和数组的集合]
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $product_id, ProductSkuService $productSkuService)
    {
        $return = ['status'=>1, 'message'=>'', 'data'=>''];
        $productArr = [];

        $attribute_value_arr = @$request->attribute_value_arr;
        $goods_value_arr = @$request->goods_value_arr;
        $product_name = @$request->product_name;
        $cat_id = @$request->cat_id;


        if(empty($attribute_value_arr)){

            $return['status'] = 0;
            $return['message'] = '属性及对应的属性值数组不能为空';
            return $return;
        }//end if()

        if(empty($goods_value_arr)){

            $return['status'] = 0;
            $return['message'] = '商品的属性及属性值的集合不能为空';
            return $return;
        }//end if()

        DB::beginTransaction();
        try {

            //第一步：删除产品已有的属性、属性值、关联的商品
            //第1步：删除产品的属性值及属性
            $prdocutAttributeValue = ProductAttributeValue::where('product_attribute.product_id', $product_id)
                                    ->leftJoin('product_attribute', 'product_attribute.id', '=', 'product_attribute_value.product_attribute_id')
                                    ->delete();

            $prdocutAttribute = ProductAttribute::where('product_id', $product_id)
                                    ->leftJoin('product_attribute_value', 'product_attribute_value.product_attribute_id', '=', 'product_attribute.id')
                                    ->delete();

            //第2步：删除产品下关联的商品
            $product_sku = ProductSku::where('product_id', $product_id)
                                    ->delete();

            //第二步：保存产品新的属性和对应的属性值
            $this->storeAttributeValue($product_id, $attribute_value_arr);

            //第三步：如果有要关联的商品，将商品id和对应的属性及属性值组信息插入到product_sku表中
            if (!empty($goods_value_arr)) {

                $productSku = $this->addRelation($product_id, $goods_value_arr);
            }//end if()

            //第四步：将产品名字和产品分类更新

            if(!empty($product_name) || !empty($product_name)){
                $products = Product::find($product_id);

                if(!empty($product_name)){
                    $products->name = $product_name;
                }
                if(!empty($product_name)){
                    $products->cat_id = $cat_id;
                }
                $products->update();
            }


        } catch (ProductException $e) {
            DB::rollback();
            throw new ProductException("编辑产品失败");

        }//end try
        DB::commit();

        return $return;


    }//end func update

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($product_id, Request $request)
    {
        DB::beginTransaction();
        try {
            $products = Product::find($product_id);

            //第一步：删除产品的属性值及属性
            $prdocutAttributeValue = ProductAttributeValue::where('product_attribute.product_id', $product_id)
                                    ->leftJoin('product_attribute', 'product_attribute.id', '=', 'product_attribute_value.product_attribute_id')
                                    ->delete();

            $prdocutAttribute = ProductAttribute::where('product_id', $product_id)
                                    ->leftJoin('product_attribute_value', 'product_attribute_value.product_attribute_id', '=', 'product_attribute.id')
                                    ->delete();

            //第二步：删除产品下关联的商品
            $product_sku = ProductSku::where('product_id', $product_id)
                                    ->delete();
            //第三步：删除产品
            $product = Product::find($product_id)->delete();

        } catch (ProductException $e) {
            DB::rollback();
            throw new ProductException("删除产品失败");

        }//end try
        DB::commit();

        $pre_url = @$request->pre_url;

        if($pre_url){

            return Redirect($pre_url);
        }else{

            return Redirect('admin/product/');
        }
        //return true;
    }//end func destory()



    /**
     * 产品关联商品时的商品搜索
     * @param  Request  $request  [description]
     * @param  Category $category [description]
     * @return [type]             [description]
     */
    public function searchGoods($product_id, Request $request, Category $category)
    {

        $return = ['status'=>0, 'message'=>'', 'data'=>''];


        //是否上下架
        $isOnSaleArr = ['0'=>'所有上下架', '1'=>'上架', '2'=>'下架'];
        $auditStatusArr = ['All'=>'所有审核状态','0'=>'未审核','1'=>'审核通过','2'=>'审核不通过'];
        $typeArr = ['-1'=>'选择类型', '0'=>'一般商品', '1'=>'e贸易商品'];
        $goodsNumberArr = ['All'=>'库存','0-50'=>'0-50','50-100'=>'50-100','100-200'=>'100-200','200-500'=>'200-500','500-'=>'500以上'];

        $search = array('cat_id'=>0, 'brand_id'=>0, 'type'=>0, 'is_on_sale'=>0,'audit_status'=>'All','goods_number'=>'All', 'goods_name'=>'', 'goods_sn'=>'');

        $product = Product::find($product_id);
        //根据产品所在分类查找该分类下的商品
        if (empty($product->cat_id)){
            $return['message'] = '商品分类不能为空';
            return $return;
        }else{

            $search['cat_id'] = $product->cat_id;
        }//end if()

        $query =  Goods::orderBy('sort_order','desc')->orderBy('add_time', 'desc')->orderBy('goods_id', 'desc');

        if (!empty($product->cat_id) && $product->cat_id!=0){
            $query = $query->where('cat_id', $product->cat_id);
            $search['cat_id'] = $product->cat_id;
        }//end if()

        if ($request->get('brand_id')!='' && $request->get('brand_id')!=0){
            $query = $query->where('brand_id', $request->get('brand_id'));
            $search['brand_id'] = $request->brand_id;
        }//end if()

        if (!empty($request->get('type')) && $request->get('type')!=-1){
            $query = $query->where('type', $request->get('type'));
            $search['type'] = $request->type;
        }//end if()

        if (!empty($request->get('goods_name'))){
            $goods_name = $request->goods_name;
            $goods_name = preg_replace('~\s{2,}~', ' ', $goods_name);

            $query = $query->where('goods_name', 'like', "%".trim($goods_name)."%");
            $search['goods_name'] = $request->goods_name;
        }//end if()

        if (!empty($request->get('goods_sn'))){
            $goods_sn = $request->goods_sn;
            $goods_sn = preg_replace('~\s{2,}~', ' ', $goods_sn);
            $query = $query->where('goods_sn', 'like', "%".$goods_sn."%");
            $search['goods_sn'] = $request->goods_sn;
        }//end if()

        if ($request->get('audit_status')!='' && $request->get('audit_status')!="All"){
            $query = $query->where('audit_status', $request->get('audit_status'));
            $search['audit_status'] = $request->audit_status;
        }//end if()

        if ($request->get('is_on_sale')!='' && $request->get('is_on_sale')!=0){
            $query = $query->where('is_on_sale', $request->get('is_on_sale'));
            $search['is_on_sale'] = $request->is_on_sale;
        }//end if()

        if ($request->get('goods_number')!='' && $request->get('goods_number')!='All'){
            $goods_number = explode('-',$request->get('goods_number'));
            if($goods_number[1]){
                $query = $query->where('goods_number','>=',$goods_number[0]);
                $query = $query->where('goods_number','<=',$goods_number[1]);

            }else{
                $query = $query->where('goods_number','>=',$goods_number[0]);
            }
            $search['goods_number'] = $request->goods_number;
        }//end if()

        /*"total" => 41
        "per_page" => 10
        "current_page" => 1
        "last_page" => 5
        "next_page_url" => "http://afuyigou.app/admin/product/searchGoods/5/1/10?page=2"
        "prev_page_url" => null
        "from" => 1
        "to" => 10
        $goods = $query->skip(1)->take(10);*/
        $goods = $query->get();

        foreach ($goods as $key => $value) {
            $cat_id = $value->cat_id;

            $categorys = Category::where('cat_id', $cat_id)->get();

            $goods[$key]['cat_name'] = @$categorys[0]->cat_name;
        }//end foreach()

        //品牌数组
        $brandInfo = Brand::all();
        $brandArr = ['0'=>'选择品牌'];
        foreach ($brandInfo as $key => $value) {
            $brandArr[$value->brand_id] = $value->brand_name;
        }//end foreach()

        //return view('admin.goods.index',compact(['goods','category', 'brandArr', 'typeArr','auditStatusArr', 'isOnSaleArr', 'activityArr', 'recommendArr','goodsNumberArr','search']));

        $return['status'] = 1;
        $return['data']['goods'] = $goods->toArray();
        $return['data']['brandArr'] = $brandArr;
        $return['data']['typeArr'] = $typeArr;
        $return['data']['auditStatusArr'] = $auditStatusArr;
        $return['data']['isOnSaleArr'] = $isOnSaleArr;
        $return['data']['goodsNumberArr'] = $goodsNumberArr;
        $return['data']['search'] = $search;

        return $return;

    }//end func searchGoods()


    /**
     * 关联产品和商品，并保存商品的属性以及对应的属性值的json字符串
     * @param  [int] $product_id        [产品id]
     * @param  [array] $goods_value_arr [商品id和对应的属性及属性值组信息, 如：array( 0=>array('goods_id'=>1337, 'attribute_value'=>array(0=>1, 1=>2)), 1=>array('goods_id'=>1339, 'attribute_value'=>array(0=>3, 1=>4)))]
     * @return mixed
     */
    private function addRelation($product_id, $goods_value_arr){

        $product_sku['product_id'] = $product_id;
        $product_skus['product_id'] = $product_id;

        DB::beginTransaction();//开启事务,开始批量操作
        try {

            foreach ($goods_value_arr as $key => $value) {

                $product_sku['goods_id'] = $value['goods_id'];
                $attribute_groups = $value['attribute_value'];

                $goods = Goods::find($product_sku['goods_id']);
                if (empty($goods)) {

                    throw new ProductException('要绑定的商品id['.$product_sku['goods_id'].']不存在');
                }//end if()

                $product_sku_obj = ProductSku::firstOrCreate($product_sku);

                if($product_sku_obj){

                    $num = 0;
                    $attribute_group = '';
                    foreach ($attribute_groups as $keys => $values) {

                        if($num==0){
                            $attribute_group = $values;
                        }else{
                            $attribute_group .= ','.$values;
                        }//end if()

                        ++$num;

                    }//end foreach

                    $product_sku_obj->attribute_group = $attribute_group;
                    $product_sku_obj->save();

                }//end if()

                $product_skus[$key]['goods_id'] = $product_sku['goods_id'];
                $product_skus[$key]['attribute_group'] = $attribute_group;

            }//end foreach()


        } catch (ProductException $e) {
            DB::rollback();
            throw new ProductException('产品关联商品失败');
        }
        DB::commit();

        return $product_skus;
    }//end func

    /**
     * [根据产品id获取产品的属性、属性值以及关联的商品及商品对应的属性]
     * @param  [type] $product_id [description]
     * @return [type]             [description]
     */
    public function getAttributeAndValue($product_id)
    {
        //第一步：根据产品id获取产品的属性及属性的值
        $products = Product::find($prodcut_id);
        $product_attribute_value  = ProductAttribute::where('product_id', $product_id)
                                    ->leftJoin('product_attribute_value', 'product_attribute.id', '=', 'product_attribute_value.product_attribute_id')
                                    ->get();
        dd($product_attribute_value);
    }//end func getAttributeAndValue

}//end class